<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-card>
      <el-form :model="queryParams" ref="queryForm" :inline="false" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="入库状态" prop="orderStatus">
              <el-radio-group v-model="queryParams.orderStatus" @change="handleQuery">
                <el-radio-button label="all">
                  全部
                </el-radio-button>
                <el-radio-button v-for="item in inspectFilterStatus" :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="billsId">
              <el-input v-model="queryParams.billsId" placeholder="请输入入库单号" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="供应商" prop="supplierName">-->
<!--              <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable-->
<!--                @keyup.enter.native="handleQuery" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="dateRange">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleDateChange"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 业务流程说明 -->
    <el-card class="mt20">
      <el-alert title="验收管理说明" type="info" :closable="false" class="mb8">
      <template #default>
        <div style="font-size: 13px; line-height: 22px;">
          <p>📋 <strong>验收流程：</strong>从入库单据中查询待验收的单据 → 执行验收（核对批号、生产日期、有效期） → 验收通过/不通过</p>
          <p>📊 <strong>数据来源：</strong>验收任务来自入库主表中状态为0（未收货）或1（已收货待验收）的单据</p>
          <p>✅ <strong>验收通过：</strong>状态更新为「已验收待上架」（状态2），记录验收人员、时间</p>
          <p>❌ <strong>验收不通过：</strong>状态标记为「异常」（状态4），记录不通过原因、人员、时间</p>
          <p>📱 <strong>PDA操作：</strong>PDA验收完成后会直接修改数据库状态，系统同步显示最新状态</p>
          <p>🔢 <strong>状态说明：</strong>0-未收货，1-已收货待验收，2-已验收待上架，3-已上架，4-异常，5-作废</p>
        </div>
      </template>
    </el-alert>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card class="stat-card" @click.native="handleStatClick('')">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.totalTasks }}</div>
            <div class="stat-label">总任务数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" @click.native="handleStatClick('1')">
          <div class="stat-item">
            <div class="stat-value pending">{{ statistics.pendingTasks }}</div>
            <div class="stat-label">待验收</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" @click.native="handleStatClick('2')">
          <div class="stat-item">
            <div class="stat-value completed">{{ statistics.completedTasks }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" @click.native="handleStatClick('4')">
          <div class="stat-item">
            <div class="stat-value exception">{{ statistics.exceptionTasks }}</div>
            <div class="stat-label">异常</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['wms:inspect:import']">导入单据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-check" size="mini" @click="handleBatchComplete"
          :disabled="!multipleSelection.length" v-hasPermi="['wms:inspect:complete']">批量完成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['wms:inspect:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-refresh" size="mini" @click="handleRefresh">刷新</el-button>
      </el-col>
    </el-row>
    </el-card>
    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="inspectList" border stripe @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单号" align="center" prop="billsId" width="180" />
      <el-table-column label="供应商" align="center" prop="billsCdName" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="billsState" width="120">
        <template slot-scope="scope">
          <el-tag :type="getBillsStateTag(scope.row.billsState)" size="small">
            {{ getBillsStateText(scope.row.billsState) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="进度" align="center" width="120">
        <template slot-scope="scope">
          <el-progress :percentage="getProgress(scope.row)" :status="getProgressStatus(scope.row)" :stroke-width="6"
            :show-text="false">
          </el-progress>
          <div class="progress-text">
            <span v-if="scope.row.billsState === '2' || scope.row.billsState === '3'">已完成</span>
            <span v-else>{{ scope.row.inspectedLines || 0 }}/{{ scope.row.totalLines || 0 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="合格数量" align="center" width="100">
        <template slot-scope="scope">
          {{ getQualifiedQuantity(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="不合格数量" align="center" width="100">
        <template slot-scope="scope">
          <span :style="{ color: getUnqualifiedQuantity(scope.row) > 0 ? '#F56C6C' : '' }">
            {{ getUnqualifiedQuantity(scope.row) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="验收人" align="center" prop="acceptUserName" width="100" />
      <el-table-column label="验收时间" align="center" prop="acceptTime" width="160" sortable="custom" />
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['wms:inspect:query']">详情</el-button>
          <el-button v-if="scope.row.billsState === '0' || scope.row.billsState === '1'" size="mini" type="text"
            icon="el-icon-check" @click="handleConfirmInspect(scope.row)"
            v-hasPermi="['wms:inspect:confirm']">确认验收</el-button>
          <el-button v-if="scope.row.billsState === '0' || scope.row.billsState === '1'" size="mini" type="text"
            icon="el-icon-warning" @click="handleMarkException(scope.row)" style="color: #F56C6C;"
            v-hasPermi="['wms:inspect:exception']">标记异常</el-button>
          <el-button v-if="scope.row.billsState === '4' || scope.row.billsState === '5'" size="mini" type="text"
            icon="el-icon-warning" @click="handleView(scope.row)" style="color: #F56C6C;">查看异常</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 验收任务详情对话框 -->
    <el-dialog title="验收任务详情" :visible.sync="detailOpen" width="1000px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="入库单号">{{ detailData.billsId }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ detailData.billsCdName }}</el-descriptions-item>
        <el-descriptions-item label="验收类型">{{ getInspectTypeText(detailData.inspectType) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getBillsStateTag(detailData.billsState)" size="small">
            {{ getBillsStateText(detailData.billsState) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="总数量">{{ detailData.totalQuantity }}</el-descriptions-item>
        <el-descriptions-item label="已验收">{{ detailData.inspectedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="合格数量">
          <span style="color: #67C23A; font-weight: bold;">{{ detailData.qualifiedQuantity }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="不合格数量">
          <span :style="{ color: detailData.unqualifiedQuantity > 0 ? '#F56C6C' : '', fontWeight: 'bold' }">
            {{ detailData.unqualifiedQuantity }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="验收人">{{ detailData.acceptUserName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="验收时间">{{ detailData.acceptTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item v-if="detailData.billsState === '4' && detailData.remark" label="异常原因" :span="2">
          <span style="color: #F56C6C;">{{ detailData.remark }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 商品明细列表 -->
      <div v-if="detailData.detailList && detailData.detailList.length > 0" style="margin-top: 20px;">
        <el-divider content-position="left"><strong>商品明细</strong></el-divider>
        <el-table :data="detailData.detailList" border stripe max-height="400">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="drugId" label="商品编码" width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="drugName" label="商品名称" min-width="150" align="center" show-overflow-tooltip />
          <el-table-column prop="drugGg" label="规格" width="80" align="center" show-overflow-tooltip />
          <el-table-column prop="drugDw" label="单位" width="80" align="center" />
          <el-table-column prop="drugNum" label="数量" width="100" align="center" />
          <el-table-column prop="drugCheckNum" label="确认数量" width="100" align="center" />
          <el-table-column prop="drugBatchNo" label="批号" width="120" align="center" show-overflow-tooltip />
          <el-table-column prop="drugPd" label="生产日期" width="120" align="center" />
          <el-table-column prop="drugExp" label="有效期" width="120" align="center" />
          <el-table-column prop="huoWei" label="货位" width="100" align="center" show-overflow-tooltip />
          <el-table-column prop="drugPZWH" label="批准文号" width="100" align="center" show-overflow-tooltip />
          <el-table-column label="库存状态" width="100" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.stockStatus === '0'" type="info" size="small">待检</el-tag>
              <el-tag v-else-if="scope.row.stockStatus === '1'" type="success" size="small">合格</el-tag>
              <el-tag v-else-if="scope.row.stockStatus === '2'" type="danger" size="small">不合格</el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- Excel导入对话框 -->
    <el-dialog title="导入入库单据" :visible.sync="importOpen" width="600px" append-to-body>
      <div style="padding: 20px;">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
          style="width: 100%;"
        >
          <i class="el-icon-upload" style="font-size: 48px; color: #C0C4CC;"></i>
          <div class="el-upload__text" style="margin-top: 10px;">
            将文件拖到此处，或<em style="color: #409EFF;">点击上传</em>
          </div>
        </el-upload>

        <div style="margin-top: 20px; text-align: center;">
          <div style="margin-bottom: 10px;">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的单据数据
          </div>
          <div style="color: #909399; font-size: 12px; margin-bottom: 10px;">
            仅允许导入xls、xlsx格式文件
          </div>
          <el-link type="primary" :underline="false" @click="importTemplate">
            <i class="el-icon-download"></i> 下载模板
          </el-link>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="importOpen = false">取 消</el-button>
        <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 确认验收对话框 -->
    <el-dialog title="确认验收" :visible.sync="confirmInspectOpen" width="500px" append-to-body>
      <div style="text-align: center; padding: 20px;">
        <i class="el-icon-question" style="font-size: 48px; color: #E6A23C; margin-bottom: 20px;"></i>
        <p style="font-size: 16px; margin-bottom: 20px;">
          确认验收入库单据：<strong>{{ currentInspectRow.billsId }}</strong> ？
        </p>
        <p style="color: #909399; font-size: 14px;">
          验收通过后，状态将从「已到货待验收」更新为「验收完成待上架」
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirmInspectOpen = false">取 消</el-button>
        <el-button type="primary" @click="executeInspectConfirm" :loading="confirmLoading">确 认</el-button>
      </div>
    </el-dialog>

    <!-- 标记异常对话框 -->
    <el-dialog title="标记异常" :visible.sync="exceptionOpen" width="600px" append-to-body>
      <el-form ref="exceptionForm" :model="exceptionForm" :rules="exceptionRules" label-width="100px">
        <el-form-item label="入库单号">
          <el-input v-model="exceptionForm.billsId" disabled />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="exceptionForm.billsCdName" disabled />
        </el-form-item>
        <el-form-item label="异常原因" prop="exceptionReason">
          <el-input v-model="exceptionForm.exceptionReason" type="textarea" :rows="4" placeholder="请输入异常原因" />
        </el-form-item>
        <el-form-item label="异常描述" prop="exceptionDesc">
          <el-input v-model="exceptionForm.exceptionDesc" type="textarea" :rows="4"
            placeholder="请详细描述异常情况（可选）" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exceptionOpen = false">取 消</el-button>
        <el-button type="danger" @click="submitException" :loading="exceptionLoading">确认标记</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInspectTask,
  completeInspectTask,
  delInspectTask,
  confirmInspect,
  markException
} from '@/api/wms/inspect'
import { getToken } from '@/utils/auth'

export default {
  name: 'WmsInspect',
  data() {
    return {
      // 列表相关
      loading: true,
      showSearch: true,
      total: 0,
      inspectList: [],
      multipleSelection: [],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billsId: null,
        orderStatus: "all",//上架管理
        supplierName: null,
        beginTime: null,
        optType: -1,//验收
        endTime: null,
        orderByColumn: null,
        isAsc: null
      },

      // 统计数据
      statistics: {
        totalTasks: 0,
        pendingTasks: 0,
        processingTasks: 0,
        completedTasks: 0,
        exceptionTasks: 0
      },

      // 详情相关
      detailOpen: false,
      detailData: {},
      // 入库状态定义（完整状态映射）
      // 0-未收货，1-已收货待验收，2-已验收待上架，3-已上架，4-异常，5-作废
      wms_receipt_status: [
        { label: '未收货', value: '0' },
        { label: '已收货待验收', value: '1' },
        { label: '已验收待上架', value: '2' },
        { label: '已上架', value: '3' },
        { label: '异常', value: '4' },
        { label: '作废', value: '5' }
      ],
      // 验收管理筛选状态（只显示验收相关状态）
      inspectFilterStatus: [
        { label: '待验收', value: '1' },
        { label: '已验收', value: '2' },
        { label: '异常', value: '4' }
      ],
      // 导入相关
      importOpen: false,
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/storage/buyStore/importData"
      },

      // 确认验收相关
      confirmInspectOpen: false,
      confirmLoading: false,
      currentInspectRow: {},

      // 异常处理相关
      exceptionOpen: false,
      exceptionLoading: false,
      exceptionForm: {},
      exceptionRules: {
        exceptionReason: [
          { required: true, message: '请输入异常原因', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getGlobalStatistics()
  },
  methods: {
    // 获取验收任务列表
    getList() {
      this.loading = true
      // 构建查询参数，确保日期范围正确传递
      const queryParams = {
        ...this.queryParams,
        beginTime: this.queryParams.beginTime,
        endTime: this.queryParams.endTime,
        optType: this.queryParams.optType,
        type:'1',
      }

      listInspectTask(queryParams).then(response => {
        this.inspectList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 获取全局统计数据（根据主表billsState统计）
    getGlobalStatistics() {
      // 获取所有数据，在前端根据 billsState 统计
      const params = {
        pageNum: 1,
        pageSize: 999999, // 获取所有数据
        optType: -1,
        type: '1',
        orderStatus: 'all'
      }

      listInspectTask(params).then(response => {
        const data = response.rows || []

        // 根据主表 billsState 字段统计各状态数量
        this.statistics.totalTasks = data.length
        this.statistics.pendingTasks = data.filter(item => item.billsState === '1').length
        this.statistics.completedTasks = data.filter(item => item.billsState === '2').length
        this.statistics.exceptionTasks = data.filter(item => item.billsState === '4').length
      }).catch(error => {
        console.error('获取统计数据失败:', error)
      })
    },

    // 处理统计卡片点击
    handleStatClick(status) {
      this.queryParams.orderStatus = status || 'all'
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 重置查询
    resetQuery() {
      this.resetForm('queryForm')
      this.dateRange = []
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      this.handleQuery()
    },

    // 日期范围变化
    handleDateChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.beginTime = dates[0]
        this.queryParams.endTime = dates[1]
      } else {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      }
    },

    // 多选变化
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },

    // 排序变化
    handleSortChange({ prop, order }) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
      this.getList()
    },

    // 批量完成
    handleBatchComplete() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请选择要完成的任务')
        return
      }

      const canCompleteItems = this.multipleSelection.filter(item => item.taskStatus === 'in_progress')
      if (!canCompleteItems.length) {
        this.$message.warning('所选任务中没有可完成的任务')
        return
      }

      this.$confirm(`确认完成选中的 ${canCompleteItems.length} 个验收任务?`, '提示', { type: 'warning' }).then(() => {
        const promises = canCompleteItems.map(item => completeInspectTask(item.id))
        Promise.all(promises).then(() => {
          this.$message.success('批量完成成功')
          this.getList()
        }).catch(() => {
          this.$message.error('批量完成失败')
        })
      })
    },

    // 导出
    handleExport() {
      this.$confirm('确认导出所有验收任务数据?', '提示', { type: 'warning' }).then(() => {
        this.$message.success('导出功能开发中...')
      })
    },

    // 刷新
    handleRefresh() {
      this.getList()
    },

    // 查看详情（修改为使用对话框显示，而不是跳转页面）
    handleView(row) {
      // 计算合格数量和不合格数量
      const qualifiedQty = this.getQualifiedQuantity(row)
      const unqualifiedQty = this.getUnqualifiedQuantity(row)

      // 直接使用当前行数据填充详情对话框
      this.detailData = {
        billsId: row.billsId,
        billsCdName: row.billsCdName,
        billsState: row.billsState,
        inspectType: row.inspectType || 'full',
        totalQuantity: row.totalQuantity || 0,
        inspectedQuantity: row.inspectedQuantity || 0,
        qualifiedQuantity: qualifiedQty,
        unqualifiedQuantity: unqualifiedQty,
        createTime: row.createTime,
        acceptUserName: row.acceptUserName || '',
        acceptTime: row.acceptTime || '',
        remark: row.remark || '', // 异常原因存储在 remark 字段
        // 保存明细列表用于展开显示
        detailList: row.inDetailList || []
      }
      this.detailOpen = true
    },

    // 完成验收
    handleComplete(row) {
      this.$confirm('确认完成验收?', '提示', { type: 'warning' }).then(() => {
        completeInspectTask(row.id).then(() => {
          this.$message.success('完成成功')
          this.getList()
        })
      })
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除?', '提示', { type: 'warning' }).then(() => {
        delInspectTask(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },

    // 导入单据
    handleImport() {
      this.importOpen = true
    },

    // 下载模板
    importTemplate() {
      // 下载导入模板
      window.open(process.env.VUE_APP_BASE_API + "/storage/buyStore/importTemplate", "_blank")
    },

    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },

    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.isUploading = false
      this.importOpen = false
      this.$refs.upload.clearFiles()

      if (response.code === 200) {
        this.$message.success('导入成功')
        this.getList()
      } else {
        this.$message.error(response.msg || '导入失败')
      }
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    // 确认验收
    handleConfirmInspect(row) {
      this.currentInspectRow = row
      this.confirmInspectOpen = true
    },

    // 执行验收确认
    executeInspectConfirm() {
      this.confirmLoading = true

      const data = {
        billsId: this.currentInspectRow.billsId,
        id: this.currentInspectRow.id,
        detailList: this.currentInspectRow.inDetailList || []
      }

      // 先调用确认验收接口
      confirmInspect(data).then(response => {
        if (response.code === 200) {
          this.$message.success('验收确认成功')
          this.confirmInspectOpen = false
          this.getList()
          this.getGlobalStatistics()
        } else {
          this.$message.error(response.msg || '验收确认失败')
        }
      }).catch(() => {
        this.$message.error('验收确认失败')
      }).finally(() => {
        this.confirmLoading = false
      })
    },

    // 标记异常
    handleMarkException(row) {
      this.exceptionForm = {
        id: row.id,
        billsId: row.billsId,
        billsCdName: row.billsCdName,
        exceptionReason: '',
        exceptionDesc: ''
      }
      this.exceptionOpen = true
      this.$nextTick(() => {
        this.$refs['exceptionForm'].clearValidate()
      })
    },

    // 提交异常标记
    submitException() {
      this.$refs['exceptionForm'].validate(valid => {
        if (valid) {
          this.exceptionLoading = true
          markException(this.exceptionForm).then(response => {
            if (response.code === 200) {
              this.$message.success('异常标记成功')
              this.exceptionOpen = false
              this.getList()
              this.getGlobalStatistics()
            } else {
              this.$message.error(response.msg || '异常标记失败')
            }
          }).catch(() => {
            this.$message.error('异常标记失败')
          }).finally(() => {
            this.exceptionLoading = false
          })
        }
      })
    },

    // 获取验收结果文本
    getInspectResultText(result) {
      return { 'qualified': '合格', 'unqualified': '不合格', 'partial': '部分合格' }[result] || result
    },

    // 获取验收类型标签类型
    getInspectTypeTag(type) {
      return { 'full': 'danger', 'sample': 'warning', 'skip': 'success' }[type] || 'info'
    },

    // 获取验收类型文本
    getInspectTypeText(type) {
      return { 'full': '全检', 'sample': '抽检', 'skip': '免检' }[type] || type
    },

    // 获取进度百分比
    getProgress(row) {
      // 如果已验收完成待上架或已上架，显示100%
      if (row.billsState === '2' || row.billsState === '3') {
        return 100
      }
      if (!row.totalLines || row.totalLines === 0) return 0
      return Math.round((row.inspectedLines || 0) / row.totalLines * 100)
    },

    // 获取进度状态
    getProgressStatus(row) {
      const progress = this.getProgress(row)
      if (progress === 100) return 'success'
      if (progress > 0) return 'active'
      return null
    },

    // 获取单据状态标签类型
    getBillsStateTag(state) {
      const mapping = {
        '0': 'info',      // 未收货
        '1': 'warning',   // 已收货待验收
        '2': 'success',   // 已验收待上架
        '3': 'success',   // 已上架
        '4': 'danger',    // 异常
        '5': 'info'       // 作废
      }
      return mapping[state] || 'info'
    },

    // 获取单据状态文本
    getBillsStateText(state) {
      const item = this.wms_receipt_status.find(s => s.value === state)
      return item ? item.label : state
    },

    // 计算合格数量（根据明细列表中stockStatus=1的数量累加）
    getQualifiedQuantity(row) {
      if (!row.inDetailList || row.inDetailList.length === 0) {
        return 0
      }
      return row.inDetailList
        .filter(item => item.stockStatus === '1')
        .reduce((sum, item) => sum + parseFloat(item.drugCheckNum || item.drugNum || 0), 0)
    },

    // 计算不合格数量（根据明细列表中stockStatus=2的数量累加）
    getUnqualifiedQuantity(row) {
      if (!row.inDetailList || row.inDetailList.length === 0) {
        return 0
      }
      return row.inDetailList
        .filter(item => item.stockStatus === '2')
        .reduce((sum, item) => sum + parseFloat(item.drugCheckNum || item.drugNum || 0), 0)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mt20 {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-item {
  padding: 10px 0;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value.pending {
  color: #909399;
}

.stat-value.processing {
  color: #E6A23C;
}

.stat-value.completed {
  color: #67C23A;
}

.stat-value.exception {
  color: #F56C6C;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.product-info {
  line-height: 1.6;
}

.product-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 2px;
}

.product-spec {
  font-size: 12px;
  color: #909399;
}

.progress-text {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
